import 'package:flutter/material.dart';
import 'Contacts.dart' show Contact, contactList, letters;
import 'constant.dart' show Appcolors;
import 'dart:async';

class contactItem extends StatelessWidget {
  final String avatar;
  final String title;
  final String groupTitle;
  final VoidCallback onPress;

  static final double MARGIN_VERTICAL = 10.0;
  static final double GROUP_TITLE_HEIGHT = 24.0;

  contactItem({@required this.avatar,
    @required this.title,
    this.groupTitle,
    this.onPress});

  bool get _isNetImgs {
    return this.avatar.startsWith('http') || this.avatar.startsWith('https');
  }

  static double _height(bool hasTitle) {
    var _itemHeight = MARGIN_VERTICAL * 2 + 37;
    if (hasTitle) {
      _itemHeight += GROUP_TITLE_HEIGHT;
    }
    return _itemHeight;
  }

  @override
  Widget build(BuildContext context) {
    Widget avatarItem;
    if (_isNetImgs) {
      avatarItem = Image.network(
        avatar,
        width: 36,
        height: 36,
      );
    } else {
      avatarItem = Image.asset(
        avatar,
        width: 36,
        height: 36,
      );
    }

    Widget sectionView() {
      return Container(
        alignment: Alignment.centerLeft,
        height: GROUP_TITLE_HEIGHT,
        padding: EdgeInsets.only(left: 10, top: 3, bottom: 3),
        color: Color(Appcolors.DividerColor),
        child: Text(groupTitle),
      );
    }

    Widget _commonItem() {
      return Container(
          margin: EdgeInsets.symmetric(horizontal: 16.0),
          padding: EdgeInsets.only(
              left: 16.0,
              right: 16.0,
              top: MARGIN_VERTICAL,
              bottom: MARGIN_VERTICAL),
          decoration: BoxDecoration(
              border: Border(
                  bottom: BorderSide(
                      width: 1, color: Color(Appcolors.DividerColor)))),
          child: Container(
              child: Row(
                children: <Widget>[
                  avatarItem,
                  Container(
                    width: 10,
                  ),
                  Text("$title")
                ],
              )));
    }

    Widget finalItemView() {
      if (groupTitle != null) {
        return Container(
          child: Column(
            children: <Widget>[sectionView(), _commonItem()],
          ),
        );
      } else {
        return _commonItem();
      }
    }

    return finalItemView();
  }
}

class ContactState extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return new _constactstate();
  }
}

class _constactstate extends State<ContactState> {
  final List<Contact> newContact = [];
  final List<contactItem> _fnItems = [
    contactItem(
        avatar: 'images/ic_new_friend.png',
        title: '新的朋友',
        onPress: () {
          print('添加新朋友。');
        }),
    contactItem(
        avatar: 'images/ic_group_chat.png',
        title: '群聊',
        onPress: () {
          print('点击了群聊。');
        }),
    contactItem(
        avatar: 'images/ic_tag.png',
        title: '标签',
        onPress: () {
          print('标签。');
        }),
    contactItem(
        avatar: 'images/ic_public_account.png',
        title: '公众号',
        onPress: () {
          print('添加公众号。');
        }),
  ];
  ScrollController _scrollController;
  Color _indexBarBG = Colors.transparent;
  Map<String, double> _letterMap = {letters[0]: 0.0};
  String _currentLetter = "";

  @override
  void dispose() {
    _scrollController.dispose();
    super.dispose();
  }

  @override
  void initState() {
    super.initState();
    _scrollController = ScrollController();
    newContact..addAll(contactList)..addAll(contactList)..addAll(contactList);
    newContact.sort((Contact contact1, Contact contact2) =>
        contact1.nameIndex.compareTo(contact2.nameIndex));

    var _totalPos = _fnItems.length * contactItem._height(false);

    for (int i = 0; i < letters.length; i++) {
      bool _hasTitle = true;
      if (i > 0 && newContact[i].nameIndex == (newContact[i - 1].nameIndex)) {
        _hasTitle = false;
      }
      if (_hasTitle) {
        _letterMap[newContact[i].nameIndex] = _totalPos;
      }

      _totalPos += contactItem._height(_hasTitle);
    }
  }

  String _getletter(BuildContext context, Offset globalPos, double tileHeight) {
    RenderBox _findRenderObject = context.findRenderObject();
    var local = _findRenderObject.globalToLocal(globalPos);
    return letters[(local.dy ~/ tileHeight).clamp(0, letters.length - 1)];
  }

  void _jumpToIndex(String letter) {
    if (letters.contains(letter) && _letterMap.containsKey(letter)) {
      _scrollController.animateTo(_letterMap[letter],
          duration: Duration(milliseconds: 300), curve: Curves.ease);
    }
  }

  List<Widget> _setLetters() {
    return letters.map((letter) {
      return Expanded(
        child: Text(letter),
      );
    }).toList();
  }

  Widget _buildIndexBar(BuildContext context, BoxConstraints container) {
    final double _totalHeight = container.biggest.height;
    final double _titleHeight = _totalHeight / letters.length;
    return GestureDetector(
      child: Column(
        children: _setLetters(),
      ),
      onVerticalDragDown: (DragDownDetails downDetail) {
        print("onVerticalDragDown");
        setState(() {
          _indexBarBG = Colors.black26;
          var indexLetter =
          _getletter(context, downDetail.globalPosition, _titleHeight);
          _currentLetter = indexLetter;
          _jumpToIndex(indexLetter);
        });
      },
      onVerticalDragStart: (DragStartDetails startDetail) {
        print("onVerticalDragStart");
      },
      onVerticalDragUpdate: (DragUpdateDetails updateDetail) {
        print("onVerticalDragUpdate");
        setState(() {
          _indexBarBG = Colors.black26;
        });
      },
      onVerticalDragEnd: (DragEndDetails endDetail) {
        print("onVerticalDragEnd");
        setState(() {
          _currentLetter = null;
          _indexBarBG = Colors.transparent;
        });
      },
      onVerticalDragCancel: () {
        print("onVerticalDragCancel");
        setState(() {
          _currentLetter = null;
          _indexBarBG = Colors.transparent;
        });
      },
    );
  }

  Future<void> _handleRefresh() {
    final Completer<void> completer = new Completer();
    Timer(Duration(milliseconds: 3000), () {
      completer.complete();
    });
    return null;
  }

  @override
  Widget build(BuildContext context) {
    return RefreshIndicator(
      onRefresh: _handleRefresh,
      child: Stack(
        children: <Widget>[
          ListView.builder(
            controller: _scrollController,
            itemBuilder: (BuildContext context, int index) {
              if (index < _fnItems.length) {
                return _fnItems[index];
              } else {
                var index2 = index - _fnItems.length;
                var contact = newContact[index2];
                bool _isShowTitle = true;
                if (index2 >= 1 &&
                    contact.nameIndex == newContact[index2 - 1].nameIndex) {
                  _isShowTitle = false;
                } else {
                  _isShowTitle = true;
                }
                return contactItem(
                  avatar: contact.avatar,
                  title: contact.name,
                  groupTitle: _isShowTitle ? contact.nameIndex : null,
                );
              }
            },
            itemCount: _fnItems.length + newContact.length,
          ),
          Positioned(
            width: 20,
            top: 0.0,
            bottom: 0.0,
            right: 0.0,
            child: Container(
              color: _indexBarBG,
              child: LayoutBuilder(builder: _buildIndexBar),
            ),
          ),
        ],
      ),
    );
  }
}
